import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:yp/config/config.dart';
import 'package:yp/services/api.dart';
import 'package:yp/utils/util.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sp_util/sp_util.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import '../../helper.dart';
import '../../router.dart';
import 'state.dart';

class OrderListLogic extends GetxController with SingleGetTickerProviderMixin {
  final state = OrderListState();
  static const platform = const MethodChannel("com.elitesland/pay");

  @override
  void onInit() {
    super.onInit();
      print('页面初始化');
   state.streamSubscription= fluwx.weChatResponseEventHandler.listen((event) {
      if (event is fluwx.WeChatLaunchMiniProgramResponse) {
        /// 取消支付：extMsg:{"errMsg":"requestPayment:fail cancel","status":"30"}
        /// 支付成功 extMsg:{"errMsg":"requestPayment:ok","status":"20"}
        print("支付结果回来了====12==${event.extMsg}");
        Map resultMap = json.decode(event.extMsg);
        if (resultMap != null) {
          if (resultMap["status"].toString() == "20") {
            print("支付结果");
              state.streamSubscription.cancel();
    state.streamSubscription.pause();
            setMoneyOver(
                SpUtil.getString('dingdan'), 1, 'Complete', 'success', 'b');
          } else {
              state.streamSubscription.cancel();

    state.streamSubscription.pause();
            setMoneyOver(SpUtil.getString('dingdan'), 0, 'List', 'err', 'b');
            toast("支付失败");
            // Get.toNamed(RouteConfig.orderList,arguments: {
            //   'status':0
            // });
          }
        } else {
            state.streamSubscription.cancel();

    state.streamSubscription.pause();
          setMoneyOver(SpUtil.getString('dingdan'), 0, 'List', 'err', 'b');
          toast("支付失败");
        }
      }
    });
   state.tabController = TabController(length: 6, vsync: this);

  }
  @override
  void onReady() {
    super.onReady();
    state.controller = TextEditingController();
    state.controller1 = RefreshController();
    if (state.orderStatus == 0) {
      state.orderStatus = Get.arguments['status'];
    }

    state.index = _getTabIndex();
    state.tabController.index = state.index; //这里赋值为index
    int customer_order_type;
    if (state.tabselectIndex == 1) {
      customer_order_type = 3;
    } else {
      customer_order_type = 99;
    }

    /// 获取我的收藏列表
    var params = {
      'usr_num_id': SpUtil.getInt('empeNumId'),
      "page": state.page,
      "page_size": 10,
      "customer_order_type": customer_order_type,
      "order_status": state.orderStatus,
      'user_type': 2,
    };
    Api.orderList(params).listen((event) {
      state.totalCount = event['total_count'];
      if (event['distribution_order_list'] != null) {
        state.orderList = event['distribution_order_list'];
        state.totalOrderMoney = event['total_order_money'] ?? 0;
      } else {
        state.orderList = [];
        state.totalOrderMoney = 0;
      }
      update();
    });

    // 查询个人购物卡
    var condition = {
      "use_platform": 2,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "card_status": 3, //购物卡状态 (1: 有效, 2:失效, 3: 可用)
      'access_token': SpUtil.getString('token'),
    };

    Api.walletInformation(condition).listen((event) {
      print('===========walletInformation==========');
      print(event);
      /*
      * {code: 0, message: 成功, full_message: null, available_cards: [],
      * invalid_cards: null, available_cards: [], valid_card_count: 0, total_card_count: 0,
      * invalid_card_count: null, total_available_amount: 0.0}
      *
      * */
      if (event['code'] == 0) {
        state.GiftcardList = event['available_cards'] ?? [];
        if (state.GiftcardList.length > 0) {
          for (var i = 0; i < state.GiftcardList.length; i++) {
            state.GiftcardList[i]['click'] = false;
          }
        }
      }
      update();
    });
  }



  // 顶部自购和分享下单页签
  void onTabSelect(int index) {
    state.tabselectIndex = index;
    int customer_order_type;
    if (index == 1) {
      customer_order_type = 3;
    } else {
      customer_order_type = 99;
    }
    state.orderList = []; // 返回值内容置空
    state.orderStatus = 0; // 订单状态未全部，即查询全部
    state.tabController.index = 0; // 定位当前tab下标
    state.page = 1;

    var params = {
      'usr_num_id': SpUtil.getInt('empeNumId'),
      "page": state.page,
      "page_size": 10,
      "customer_order_type": customer_order_type,
      "order_status": 0,
      'user_type': 2,
    };

    Api.orderList(params).listen((event) {
      double num = 0.0;
      state.totalCount = event['total_count'];
      if (event['distribution_order_list'] != null) {
        state.orderList = event['distribution_order_list'];
        // state.orderList.forEach((element) {
        //   num += element['commission_amount'] ?? 0;
        // });
      } else {
        state.orderList = [];
      }
      state.totalOrderMoney = event['total_order_money'] ?? 0;
      update();
    });
  }
  void onSelect(int index) {
    state.selectIndex = index;
    // 调用接口 刷新listVIew
    update();
  }
  /// 搜索
  void onSearch(String value) {
    state.value = value;
    // 调用接口 刷新listVIew
    int customer_order_type;
    if (state.tabselectIndex == 1) {
      customer_order_type = 3;
    } else {
      customer_order_type = 99;
    }
    var params = {
      'usr_num_id': SpUtil.getInt('empeNumId'),
      "page": state.page,
      "page_size": 10,
      "customer_order_type": customer_order_type,
      "order_status": state.orderStatus,
      'user_type': 2,
      'consumer_name': value
    };
    Api.orderList(params).listen((event) {
      double num = 0.0;
      state.totalCount = event['total_count'];
      if (event['distribution_order_list'] != null) {
        state.orderList = event['distribution_order_list'];
        // state.orderList.forEach((element) {
        //   num += element['commission_amount'] ?? 0;
        // });
      } else {
        state.orderList = [];
      }
      state.totalOrderMoney = event['total_order_money'] ?? 0;
      state.controller1.refreshCompleted(resetFooterState: true);
      update();
    });
  }

  /// 拉起中金支付
  void startCPCNWeixinPay(String authCode) async {
    if (authCode.isEmpty) {
      toast("签名失败");
      return;
    }

    var result =
        await fluwx.payWithCPCN(appId: Config.WECHAT_APPID, authCode: authCode);

    // var result = fluwx.openWeChatApp();

    print("=========结果<<<$result>>>====");
  }

  // void setAll_payment(money){
  //   state.total['all_payment'] = money;
  // }

  void goToMoney(id, moneyNum) {
    var params1 = {
      'access_token': SpUtil.getString('token'),
      "out_trade_no": id,
      "plat_type": 7,
      "body": "jifen",
      "pay_way": 0,
      "use_platform": 2,
      'appid': Config.ZJ_APPID,
    };

    // print('=============================================================');
    // print(state.total['all_payment']);
    // return;

    gotomoney(state, startCPCNWeixinPay, params1, id);

    // print('=========goToMoney==========>');
    // print(goToMoney);
    // var card_nos = [];
    // double zong = 0;
    // if (state.giftCardList.length > 0) {
    //   for (var i = 0; i < state.giftCardList.length; i++) {
    //     if (state.giftCardList[i]['click']) {
    //       card_nos.add(state.giftCardList[i]['card_no']);
    //       zong = zong + state.giftCardList[i]['money_available'];
    //     }
    //   }
    //   params1['shopping_card_pays'] = [
    //     {"pay_type_id": 15, "card_nos": card_nos, "pay_amount": zong}
    //   ];
    // }
    // Api.orderPayment(params1).listen((event) {
    //   state.dingdan = event['tml_num_id'];
    //   state.shifu = event['pay_response']['coupon_fee'];
    //   if (event["code"] == 0 && event["pre_pay_no"] == null) {
    //     Get.toNamed(RouteConfig.orderComplete,arguments: {
    //       'dingdan':event['tml_num_id'],
    //       'shifu':event['pay_response']['coupon_fee']
    //     }).then((value){
    //       onReady();
    //     });
    //   } else if (event["code"] == 0 && event["pre_pay_no"] != null) {
    //     startCPCNWeixinPay(event['pre_pay_no']);
    //   } else {
    //     toast(event['message']);
    //   }
    // });
  }

  void onSwitch(int index) {
    state.currentTab = index;
    // 调用接口 刷新listVIew
    update();
  }

  void onTabChange(int index) {
    print('====onTabChange=====');
    state.index = index;
    state.tabController.index = state.index; //这里赋值为index
    _upgradeStateOrderStatus();
    print(state.index);
    print(state.orderStatus);

    int customer_order_type;
    if (state.tabselectIndex == 1) {
      customer_order_type = 3;
    } else {
      customer_order_type = 99;
    }

    state.page = 1;
    var params = {
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'user_type': 2,
      "page": state.page,
      "page_size": 10,
      "customer_order_type": customer_order_type,
      "order_status": state.orderStatus,
      'consumer_name': state.value
    };
    Api.orderList(params).listen((event) {
      double num = 0.0;
      state.totalCount = event['total_count'];
      if (event['distribution_order_list'] != null) {
        state.orderList = event['distribution_order_list'];
        // state.orderList.forEach((element) {
        //   num += element['commission_amount'] ?? 0;
        // });
      } else {
        state.orderList = [];
      }
      state.totalOrderMoney = event['total_order_money'] ?? 0;
      update();
    });
  }

  /// 下拉刷新
  void refreshData() {
    state.orderList = [];
    state.page = 1;
    int customer_order_type;
    if (state.tabselectIndex == 1) {
      customer_order_type = 3;
    } else {
      customer_order_type = 99;
    }
    _upgradeStateOrderStatus();
    // int index = state.index;
    // int a;
    // if (index == 0) {
    //   a = 0;
    // } else if (index == 1) {
    //   a = 1;
    // } else if (index == 2) {
    //   a = 6;
    // } else if (index == 3) {
    //   a = 3;
    // } else if (index == 4) {
    //   a = 4;
    // } else if (index == 5) {
    //   a = 17;
    // }
    var params = {
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'user_type': 2,
      "page": state.page,
      "page_size": 10,
      "customer_order_type": customer_order_type,
      "order_status": state.orderStatus,
      'consumer_name': state.value
    };
    Api.orderList(params).listen((event) {
      double num = 0.0;

      if (event['code'] == 0) {
        state.totalCount = event['total_count'];
        if (event['distribution_order_list'] != null) {
          state.orderList = event['distribution_order_list'];
          // state.orderList.forEach((element) {
          //   num += element['commission_amount'] ?? 0;
          // });
          state.controller1.refreshCompleted(resetFooterState: true);
        } else {
          state.orderList = [];
          state.controller1.refreshCompleted(resetFooterState: true);
          state.controller1.loadNoData();
        }
      } else {
        state.controller1.refreshCompleted(resetFooterState: true);
        state.controller1.loadNoData();
      }
      state.totalOrderMoney = event['total_order_money'] ?? 0;
      update();
    });
  }

  /// 上拉加载更多
  void loadMoreData() {
    state.page = state.page + 1;
    int customer_order_type;
    if (state.tabselectIndex == 1) {
      customer_order_type = 3;
    } else {
      customer_order_type = 99;
    }
    _upgradeStateOrderStatus();
    // int index = state.index;
    // int a;
    // if (index == 0) {
    //   a = 0;
    // } else if (index == 1) {
    //   a = 1;
    // } else if (index == 2) {
    //   a = 6;
    // } else if (index == 3) {
    //   a = 3;
    // } else if (index == 4) {
    //   a = 4;
    // } else if (index == 5) {
    //   a = 17;
    // }
    var params = {
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'user_type': 2,
      "page": state.page,
      "page_size": 10,
      "customer_order_type": customer_order_type,
      "order_status": state.orderStatus,
      'consumer_name': state.value
    };
    Api.orderList(params).listen((event) {
      // double num = 0.0;
      state.totalCount = event['total_count'];
      List list = state.orderList;
      if (event['distribution_order_list'].length > 0) {
        list.addAll(event['distribution_order_list']);
        // state.orderList.forEach((element) {
        //   num += element['commission_amount'] ?? 0;
        // });
        state.orderList = list;
        state.controller1.loadComplete();
      } else {
        state.controller1.loadNoData();
      }
      state.totalOrderMoney = event['total_order_money'] ?? 0;
      update();
    });
  }

  void dispose() {
    super.dispose();
    state.controller1.dispose();
  }

  // add by gyq
  int _getTabIndex() {
    int index = 0;
    int orderstatus = state.orderStatus;
    print('_getTabIndex===');
    print(orderstatus);
    switch (orderstatus) {
      case 1:
        index = 1;
        break;
      case 2:
        index = 2;
        break;
      case 3:
        index = 3;
        break;
      case 4:
        index = 4;
        break;
      case 17:
        index = 5;
        break;
    }
    return index;
  }

  void _upgradeStateOrderStatus() {
    switch (state.index) {
      case 0:
        state.orderStatus = 0;
        break;
      case 1:
        state.orderStatus = 1;
        break;
      case 2:
        state.orderStatus = 2;
        break;
      case 3:
        state.orderStatus = 3;
        break;
      case 4:
        state.orderStatus = 4;
        break;
      case 5:
        state.orderStatus = 17;
        break;
    }
  }

  void _queryData() {
    int customer_order_type;
    if (state.tabselectIndex == 1) {
      customer_order_type = 3;
    } else {
      customer_order_type = 99;
    }
    var params = {
      'usr_num_id': SpUtil.getInt('empeNumId'),
      "page": state.page,
      "page_size": 10,
      "customer_order_type": customer_order_type,
      "order_status": state.orderStatus,
      'user_type': 2,
    };
    Api.orderList(params).listen((event) {
      print('=======更新后查询结果==========');
      print(event);
      state.totalCount = event['total_count'];
      if (event['distribution_order_list'] != null) {
        state.orderList = event['distribution_order_list'];
        state.totalOrderMoney = event['total_order_money'] ?? 0;
      } else {
        state.orderList = [];
        state.totalOrderMoney = event['total_order_money'] ?? 0;
      }
      update();
    });
  }

  void _submitApply(data) {
    /// 获取订单详情
    var params = {
      'access_token': SpUtil.getString('token'),
      'tml_operation_type': 3,
      'tml_num_id': data['tml_num_id'],
      'usr_num_id': SpUtil.getInt('empeNumId'),
    };

    Api.cxtk(params).listen((event) {
      if (event['code'] == 0) {
        toast('撤销成功');
        _queryData();
      } else {
        toast(event['message']);
      }
    });
  }

  // 确认收货
  void _confirmRec(data) {
    /// 获取订单详情
    var params = {
      'access_token': SpUtil.getString('token'),
      'tml_num_id': data['tml_num_id'],
      'usr_num_id': SpUtil.getInt('empeNumId'),
    };

    Api.confirmReceived(params).listen((event) {
      if (event['code'] == 0) {
        toast('确认收货成功');
        _queryData();
      } else {
        toast(event['message']);
      }
    });
  }

  /**
   * type = '0', 继续付款
   * type = '1', 取消订单
   * */
  void optOrder(data, type) {
    var params;
    if (type == '0') {
      print('=======继续付款==========');
      goToMoney(data['tml_num_id'], data['total_amount']);
    } else if (type == '1') {
      print('=======取消订单==========');
      params = {
        'tml_num_id': data['tml_num_id'],
        'usr_num_id': SpUtil.getInt('empeNumId'),
      };
      Api.closeOrder(params).listen((event) {
        if (event['code'] == 0) {
          toast("操作成功");
          _queryData();
        } else {
          toast(event["message"]);
        }
        update();
      });
    } else if (type == '2') {
      print('=======撤销申诉==========');
      _submitApply(data);
    } else if (type == '3') {
      print('=======确认收货==========');
      _confirmRec(data);
    }
  }

  void setGift(index) {
    print(state.isGiftMoney);
    setcard(state, index);
    update();
    // state.isGiftNum = 0;
    // for (var i = 0; i < state.giftCardList.length; i++) {
    //   if(i == index){
    //     state.giftCardList[i]['click'] = !state.giftCardList[i]['click'];
    //   }
    //   if(state.giftCardList[i]['click']){
    //     state.isGiftNum++;
    //   }
    // }
  }

  // 小数转换为整数
  int fmtDouble2Int(double num) {
    print(num);
    if (num < 0) {
      num = 0.0;
    }
    int res = num.toInt();
    return res;
  }

  // 计算选择的卡金额
  calculateCardAmount() {
    var amt = 0.0;
    if (state.GiftcardList.length == 0) {
      return amt;
    }

    for (var i = 0; i < state.GiftcardList.length; i++) {
      if (state.GiftcardList[i]['click']) {
        amt = amt + state.GiftcardList[i]['money_available'];
      }
    }
    return amt;
  }

  //点击去付款 微信付款或支付宝付款
  // card_type 如果 1， 不需要查询购物卡，直接调微信支付，如果是 0， 需要查询福利卡，减去福利卡金额  （total_amount）- 福利卡金额
  void toPay(data) {}
}
